package org.sonar.server.platform.db.migration.charset;

import java.sql.Connection;
import java.sql.SQLException;
import org.slf4j.LoggerFactory;
import org.sonar.api.utils.MessageException;

import static java.lang.String.format;
import static org.apache.commons.lang3.StringUtils.containsIgnoreCase;

class OceanbaseCharsetHandler extends CharsetHandler {

	OceanbaseCharsetHandler(SqlExecutor selectExecutor) {
		super(selectExecutor);
	}

	@Override
	public void handle(Connection connection, DatabaseCharsetChecker.State state) throws SQLException {
		if (state == DatabaseCharsetChecker.State.FRESH_INSTALL) {
			LoggerFactory.getLogger(getClass()).info("Verify that database charset is UTF8");
			expectUtf8(connection);
		}
	}

	private void expectUtf8(Connection connection) throws SQLException {
		String charset = getSqlExecutor().selectSingleString(connection, "select default_character_set_name from information_schema.schemata where schema_name='sonarqube'");
		if (!containsIgnoreCase(charset, UTF8)) {
			throw MessageException.of(format("Oceanbase_mysql default_character_set_name does not support UTF8: %s", charset));
		}
	}
}
